package com.cy.interceptor;

import com.cy.anno.Security;
import com.cy.pojo.Handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author ChenYan
 * @Date 2021/8/3 13:39
 * @Description
 */
public class PermissionInterceptor implements HandleInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Handler handler) throws Exception {
        System.out.println("被 PermissionInterceptor 拦截");

        //如果方法上面标了Security，那么就验证权限
        if (handler.getMethod().isAnnotationPresent(Security.class)){
            Security security = handler.getMethod().getAnnotation(Security.class);
            String[] annUsernames = security.value();
            String username = request.getParameter("username");
            if (annUsernames.length > 0){
                for (String annUsername : annUsernames) {
                    if (!"".equals(annUsername) && annUsername.equals(username)){
                        return true;
                    }
                }
                response.getWriter().write("no permission");
                return false;
            }
        }

        //如果类上面标了Security，那么就验证权限
        if (handler.getController().getClass().isAnnotationPresent(Security.class)){
            Security security = handler.getController().getClass().getAnnotation(Security.class);
            String[] annUsernames = security.value();
            String username = request.getParameter("username");
            if (annUsernames.length > 0){
                for (String annUsername : annUsernames) {
                    if (!"".equals(annUsername) && annUsername.equals(username)){
                        return true;
                    }
                }
                response.getWriter().write("no permission");
                return false;
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
